#include <iostream>
#include <fstream>
#include <thread>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <fcntl.h>
#include <poll.h>

#include <csignal>
#include <atomic>
#include <memory>
#include <sys/ioctl.h>
#include <fcntl.h>

// #include "./class_device_232.h"
// #include "./class_device_485.h"
// #include "./class_gettimestr.h"
// #include "./class_libxml.h"
// #include "./class_sqlite.h"
#include "./class_tcp.h"
#include "class_modbus.h"

using namespace std;
int main_running = 1;

class_TCP tcpserver;
static void thfunc_TCP()
{
    if(0 < tcpserver.initTCPserver())
    {
        tcpserver.runTCPserver();
    }

}

static void thfunc_232()
{

}

class_modbus* p_modbus = class_modbus::getHandle();
static void thfunc_modbus()
{
    if(p_modbus->initModbus() > 0)
    {
        while(main_running > 0)
        {
            p_modbus->readData();
            if(p_modbus->readrst > 1)
                tcpserver.sendTW(p_modbus->temperature,p_modbus->wet);
            usleep(2000000);
        }
    }
    cout << "thfunc_modbus exit "<<endl;
}

void handle_sigint(int signum) {
    if (signum == SIGINT) {
        cout << "handle_sigint:"<<signum<< endl;
        tcpserver.run = -1;
        main_running = -1;
    }
}

int main(int argc, char *argv[])
{
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = handle_sigint;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, nullptr);

    // std::thread* pthrd232 = nullptr;
    std::thread* pthrdmodbus = nullptr;
    std::thread* pthrdTCP = nullptr;

    pthrdTCP = new std::thread(thfunc_TCP);
    // pthrdmodbus = new std::thread(thfunc_modbus);

    while(main_running > 0)
    {
        usleep(100000);
    }

    if(pthrdTCP != nullptr){
        if(pthrdTCP->joinable())
            pthrdTCP->join();
    }

    if(pthrdmodbus != nullptr){
        if(pthrdmodbus->joinable())
            pthrdmodbus->join();
    }

    return 0;

}






